/*
 * Copyright (c) 2006-2020, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2020-05-21     chenhy       the first version
 */
#include "board.h"
#include "spi.h"
SPI_HandleTypeDef hspi2;
int spi2_init(void)
{
  hspi2.Instance = SPI2;
  hspi2.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8;
  hspi2.Init.Direction = SPI_DIRECTION_2LINES;
  hspi2.Init.CLKPhase = SPI_PHASE_1EDGE;
  hspi2.Init.CLKPolarity = SPI_POLARITY_LOW;
  hspi2.Init.CRCCalculation = SPI_CRC_LENGTH_DATASIZE;
  hspi2.Init.CRCPolynomial = 7;
  hspi2.Init.DataSize = SPI_DATASIZE_8BIT;
  hspi2.Init.FirstBit = SPI_FIRSTBIT_MSB;
  hspi2.Init.NSS = SPI_NSS_SOFT;
  hspi2.Init.TIMode = SPI_TIMODE_DISABLE;
  hspi2.Init.NSSPMode = SPI_NSS_PULSE_DISABLE;
  hspi2.Init.CRCLength = SPI_CRC_LENGTH_8BIT;
  hspi2.Init.Mode = SPI_MODE_MASTER;
  HAL_SPI_DeInit(&hspi2);
  HAL_SPI_Init(&hspi2);
  return 0;
}
INIT_DEVICE_EXPORT(spi2_init);

uint8_t spi2_rw(uint8_t data)
{
  uint8_t value;
  HAL_SPI_TransmitReceive(&hspi2, &data, &value, 1, HAL_MAX_DELAY);
  return value;
}

void HAL_SPI_MspInit(SPI_HandleTypeDef *hspi)
{
  GPIO_InitTypeDef GPIO_InitStruct;
  if (hspi->Instance == SPI2) {
    __HAL_RCC_GPIOB_CLK_ENABLE();
    __HAL_RCC_SPI2_CLK_ENABLE();
    GPIO_InitStruct.Pin = GPIO_PIN_13|GPIO_PIN_14|GPIO_PIN_15;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_PULLDOWN;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    GPIO_InitStruct.Alternate = GPIO_AF0_SPI2;
    HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
  }
}

void HAL_SPI_MspDeInit(SPI_HandleTypeDef *hspi)
{
  if(hspi->Instance == SPI2) {
    __HAL_RCC_SPI2_FORCE_RESET();
    __HAL_RCC_SPI2_RELEASE_RESET();
    HAL_GPIO_DeInit(GPIOB, GPIO_PIN_13|GPIO_PIN_14|GPIO_PIN_15);
  }
}
